<template>
  <el-dialog v-model="visible" width="900px" :append-to-body="true" title="联系人矩阵" @close="closeDialog">
    <el-button size="small" type="primary" :icon="Plus" style="margin-bottom: 5px" @click="openForm(null)">添加</el-button>
    <el-table :data="tableList" size="small" border stripe :header-cell-style="{textAlign: 'center', background: 'var(--el-color-primary-light-9)', color: 'var(--next-bg-menuBar-light-1)'}" :cell-style="{textAlign: 'center'}">
      <el-table-column label="联系人" prop="name"/>
      <el-table-column label="职位" prop="job" width="100"/>
      <el-table-column label="角色" prop="role" width="100"/>
      <el-table-column label="联系方式" prop="phone"/>
      <el-table-column label="微信号" prop="wechat">
        <template v-slot="{row}">{{ row.isWechat == 0 ? row.phone : row.wechat }}</template>
      </el-table-column>
      <el-table-column label="主要联系人" prop="default" align="center" width="110">
        <template v-slot="{row}">
          <el-switch v-model="row.isMain" size="default" :active-value="0" :inactive-value="1" active-text="是" inactive-text="否" @change="mainChange(row)"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark"/>
      <el-table-column label="操作" fixed="right" width="140" align="center">
        <template v-slot="{row}">
          <el-button :icon="Edit" type="primary" text @click="openForm(row)" link size="small">编辑</el-button>
          <el-button :icon="Delete" type="danger" text @click="delContact(row)" link size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="formVisible" width="500px" :append-to-body="true" :title="formData.id ? '编辑' : '添加'">
      <el-form :model="formData" :rules="formRules" label-width="100px" ref="formRef" size="small">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请填写名称" clearable maxlength="16" style="width: 240px;margin-right: 10px"/>
          <el-checkbox v-model="formData.isMain" label="主要联系人" size="small" :true-label="0" :false-label="1"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请填写联系电话" clearable maxlength="16" style="width: 240px;margin-right: 10px"/>
          <el-checkbox v-model="formData.isWechat" label="微信同号" size="small" :true-label="0" :false-label="1"/>
        </el-form-item>
        <el-form-item label="微信" prop="wechat" v-if="formData.isWechat == 1">
          <el-input v-model="formData.wechat" placeholder="请填写微信号/手机号" maxlength="32" clearable/>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-input v-model="formData.role" placeholder="请填写角色" clearable maxlength="32"/>
        </el-form-item>
        <el-form-item label="职位" prop="job">
          <el-input v-model="formData.job" placeholder="请填写职位" clearable maxlength="32"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="3"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" @click="formVisible = false">关闭</el-button>
        <el-button size="small" type="primary" :loading="submitLoad" @click="saveContact(formRef)">保存</el-button>
      </template>
    </el-dialog>

    <template #footer>
      <el-button type="primary" size="small" @click="visible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {computed, reactive, toRefs, ref} from 'vue'
import {Delete, Plus, Edit} from '@element-plus/icons-vue'
import {ElMessageBox, ElMessage} from 'element-plus'
import {removeContact, getCustomerContacts, addContact, editContact, modifyMain} from '/@/api/ums/customer/contact'

export default {
  name: 'ContactTable',
  props: {
    dialogPop: {
      type: Boolean,
      default: false
    },
    customerId: {
      type: String,
      default: null
    },
    contactList: {
      type: Array,
      default: []
    }
  },
  emits: ['update:dialogPop', 'update:contactList'],
  setup(props, context) {
    const formRef = ref()
    const {dialogPop, contactList, customerId} = toRefs(props)
    const visible = computed({
      get: () => {
        if (dialogPop.value) {
          state.tableList = contactList
        }
        return dialogPop.value
      },
      set: val => context.emit('update:dialogPop', val)
    })
    const state = reactive({
      tableList: [],
      formData: {
        id: null,
        memberId: null,
        name: null,
        phone: null,
        isWechat: 0,
        wechat: null,
        job: null,
        role: null,
        isMain: 1
      },
      formRules: {
        name: {required: true, message: '请填写联系人名称', trigger: 'blur'},
        phone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {pattern: /^[1]([3-9])[0-9]{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
        ]
      },
      formVisible: false,
      submitLoad: false
    })

    // 获取客户联系人列表
    const getList = () => getCustomerContacts(customerId.value).then(res => state.tableList = res.data).catch(e => console.log(e))
    const closeDialog = () => context.emit('update:contactList', state.tableList)
    // 打开编辑
    const openForm = (item) => {
      if (item && item.id) {
        state.formData = JSON.parse(JSON.stringify(item))
      } else {
        state.formData = {
          id: null,
          memberId: customerId.value,
          name: null,
          phone: null,
          isWechat: 0,
          wechat: null,
          job: null,
          role: null,
          isMain: 1
        }
      }
      state.formVisible = true
    }
    // 删除联系人
    const delContact = (item) => {
      ElMessageBox.confirm('确定删除联系人 ' + item.name + ' ？', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        buttonSize: 'small',
        type: 'warning'
      }).then(() => {
        removeContact(item).then(res => {
          if (res.data) {
            getList()
            ElMessage.success('删除成功！')
          }
        }).catch(e => console.log(e))
      }).catch(() => {
      })
    }
    // 保存联系人
    const saveContact = (formEl) => {
      formEl.validate(async (valid) => {
        if (!valid) {
          return
        }
        let res
        state.submitLoad = true
        try {
          if (state.formData.id) {
            res = await editContact(state.formData)
          } else {
            res = await addContact(state.formData)
          }
          if (res.data) {
            getList()
            state.formVisible = false
            ElMessage.success('保存成功！')
          }
        } catch (e) {
          console.log(e)
        }
        state.submitLoad = false
      })
    }
    // 修改主要联系人
    const mainChange = (item) => {
      modifyMain({
        id: item.id,
        memberId: item.memberId,
        isMain: item.isMain
      }).then(res => {
        if (res.data) {
          for (let i = 0; i < state.tableList.length; i++) {
            let contact = state.tableList[i]
            if (contact.isMain == 0 && contact.id != item.id) {
              contact.isMain = 1
              break
            }
          }
          ElMessage.success('修改成功！')
        }
      }).catch(e => console.log(e))
    }

    return {
      visible,
      Delete,
      Edit,
      Plus,
      formRef,
      ...toRefs(state),
      closeDialog,
      delContact,
      saveContact,
      openForm,
      mainChange
    }
  }
}
</script>

<style scoped lang="scss">
</style>
